using Microsoft.AspNetCore.Mvc;
using MVCWeekOne.Models;
using System.Text;
using System.Text.Json;

namespace MVCWeekOne.Controllers
{
    /// <summary>
    /// 销售订单控制器
    /// </summary>
    public class SalesOrderController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly HttpClient _httpClient;

        public SalesOrderController(IConfiguration configuration, HttpClient httpClient)
        {
            _configuration = configuration;
            _httpClient = httpClient;
        }

        /// <summary>
        /// 销售订单列表页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 新增销售订单页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// 打印销售订单页面
        /// </summary>
        /// <param name="id">销售订单ID</param>
        /// <returns></returns>
        public IActionResult Print(int id)
        {
            ViewBag.SalesOrderId = id;
            return View();
        }

        /// <summary>
        /// 查询销售订单列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="orderNo">单据编号</param>
        /// <param name="remark">备注</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QuerySalesOrder(int pageIndex = 1, int pageSize = 10, string? orderNo = null, string? remark = null)
        {
            try
            {
                var url = $"{_configuration["ApiSettings:ReadApiUrl"]}/SalesOrder/QuerySalesOrder?pageIndex={pageIndex}&pageSize={pageSize}&orderNo={orderNo}&remark={remark}";
                var response = await _httpClient.GetAsync(url);
                var result = await response.Content.ReadAsStringAsync();

                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 查询销售订单产品明细
        /// </summary>
        /// <param name="salesOrderId">销售订单ID</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QuerySalesOrderProduct(int salesOrderId, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var url = $"{_configuration["ApiSettings:ReadApiUrl"]}/SalesOrder/QuerySalesOrderProduct?salesOrderId={salesOrderId}&pageIndex={pageIndex}&pageSize={pageSize}";
                var response = await _httpClient.GetAsync(url);
                var result = await response.Content.ReadAsStringAsync();

                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取产品选择列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="productCode">产品编号</param>
        /// <param name="productName">产品名称</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetProductSelect(int pageIndex = 1, int pageSize = 30, string? productCode = null, string? productName = null)
        {
            try
            {
                var url = $"{_configuration["ApiSettings:ReadApiUrl"]}/SalesOrder/GetProductSelect?pageIndex={pageIndex}&pageSize={pageSize}&productCode={productCode}&productName={productName}";
                var response = await _httpClient.GetAsync(url);
                var result = await response.Content.ReadAsStringAsync();

                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 新增销售订单
        /// </summary>
        /// <param name="request">请求数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddSalesOrder([FromBody] object request)
        {
            try
            {
                var json = JsonSerializer.Serialize(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync($"{_configuration["ApiSettings:WriteApiUrl"]}/SalesOrder/AddSalesOrder", content);
                var result = await response.Content.ReadAsStringAsync();

                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = ex.Message });
            }
        }

        /// <summary>
        /// 更新销售订单
        /// </summary>
        /// <param name="request">请求数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateSalesOrder([FromBody] object request)
        {
            try
            {
                var json = JsonSerializer.Serialize(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync($"{_configuration["ApiSettings:WriteApiUrl"]}/SalesOrder/UpdateSalesOrder", content);
                var result = await response.Content.ReadAsStringAsync();

                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = ex.Message });
            }
        }

        /// <summary>
        /// 删除销售订单
        /// </summary>
        /// <param name="request">请求数据</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DeleteSalesOrder([FromBody] object request)
        {
            try
            {
                var json = JsonSerializer.Serialize(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync($"{_configuration["ApiSettings:WriteApiUrl"]}/SalesOrder/DeleteSalesOrder", content);
                var result = await response.Content.ReadAsStringAsync();

                return Content(result, "application/json");
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = ex.Message });
            }
        }

        /// <summary>
        /// 导出销售订单
        /// </summary>
        /// <param name="orderNo">单据编号</param>
        /// <param name="remark">备注</param>
        /// <param name="includeProductDetails">是否包含产品明细</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportSalesOrder(string? orderNo = null, string? remark = null, bool includeProductDetails = true)
        {
            try
            {
                var url = $"{_configuration["ApiSettings:ReadApiUrl"]}/SalesOrder/ExportSalesOrder?orderNo={orderNo}&remark={remark}&includeProductDetails={includeProductDetails}";
                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsByteArrayAsync();
                    
                    // 直接使用前端生成的文件名，避免中文编码问题
                    var fileName = $"销售订单_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    
                    return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
                }

                return Json(new { success = false, message = "导出失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
}
